<script setup>
import {nextTick, onBeforeUnmount, onMounted, ref} from "vue";
import loading from "@/utils/loading";
import {Terminal} from "xterm";
import {FitAddon} from "xterm-addon-fit";
import {useRoute} from 'vue-router'
import local from '@/axios/local'
import "xterm/css/xterm.css";

const itemData = ref()
const terminalRef = ref()
const route = useRoute()
const fitAddon = ref()
const socket = ref(window.$io)
const terminal = ref()

function initTerm(data) {
  loading.show()
  let t = new Terminal({
    cols: 80,
    rows: 24,
    // 光标闪烁
    cursorBlink: true,
    lineHeight: 1.2,
    fontSize: 12,
    fontFamily: "Monaco, Menlo, Consolas, 'Courier New', monospace",
    cursorStyle: 'underline',
    scrollback: 100,
    tabStopWidth: 4,
    theme: {
      background: '#1e1e1e',
      foreground: '#c5c8c6',
    },
  });
  terminal.value = t
  terminal.value.open(terminalRef.value);
  fitAddon.value = new FitAddon();
  terminal.value.loadAddon(fitAddon.value)

  setTimeout(() => {
    fitAddon.value.fit()
  }, 5)
  let p = {
    type: 'resize',
    data: data,
    cols: t.cols,
    rows: t.rows,
  }
  socket.value.emit('ssh.sendData', p)
  terminal.value.onData(v => {
    socket.value.emit('ssh.sendData', {
      type: 'data',
      data: data,
      value: v
    })
  })
  socket.value.on(`term_data_${data.uuid}`, r => {
    console.log(r, 'rr')
    terminal.value.write(r.value);
  })

  loading.hidden()
}


function setSize() {
  socket.value.emit('ssh.sendData', {
    type: 'resize',
    data: {
      uuid: itemData.value.uuid
    },
    cols: terminal.value.cols,
    rows: terminal.value.rows
  })
}

function resize() {
  try {
    fitAddon.value.fit();
    nextTick(function () {
      setSize()
    })
  } catch (e) {
    console.log(e)
  }
}

async function getItem() {
  const r = useRoute()
  console.log(r)
  let {data} = await local.get(`/ssh/getItemById?id=${r.query.id}`)
  itemData.value = data
  initTerm(data)
}

onBeforeUnmount(() => {
  console.log(22222222)
  socket.value.emit('ssh.closeSSh', {uuid: itemData.value.uuid})
})
onMounted(() => {
  window.addEventListener('resize', resize)
  getItem()
})
</script>

<template>
  <div ref="terminalRef" class="terminal-container"></div>
</template>

<style scoped lang="scss">
::v-deep(.xterm ) {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  text-align: left !important;
  padding: 5px;

}


.terminal-container {
  width: 100%;
  height: 100%;
}

</style>